<?php

/*
 *  Copyright (c) Niels Orsleff Justesen <njustesen@gmail.com> and Nicholas Mossor Rathmann <nicholas.rathmann@gmail.com> 2007-2009. All Rights Reserved.
 *      
 *
 *  This file is part of OBBLM.
 *
 *  OBBLM is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  OBBLM is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *   
 */

function match_form($match_id) {

    // Is $match_id valid?
    if (!get_alt_col('matches', 'match_id', $match_id, 'match_id'))
        fatal("Invalid match ID.");
    
    global $stars;
    global $rules;
    global $lng;
    
    $easyconvert = new array_to_js();
    @$easyconvert->add_array($stars, 'phpStars'); // Load stars array into JavaScript array.
    echo $easyconvert->output_all();

    echo '<script language="JavaScript" type="text/javascript">
    var ID_MERCS = '.ID_MERCS.';
    var ID_STARS_BEGIN = '.ID_STARS_BEGIN.';    
    </script>
    ';
   
    // Create objects
    $coach = (isset($_SESSION['logged_in'])) ? new Coach($_SESSION['coach_id']) : null;
    $m = new Match($match_id);
    $team1 = new Team($m->team1_id);
    $team2 = new Team($m->team2_id);
    
    // Determine visitor privileges.
    $ALLOW_EDIT = false;

    if (!$m->locked && is_object($coach) && ($coach->admin || $coach->isInMatch($m->match_id)))
        $ALLOW_EDIT = true;
    
    $DIS = ($ALLOW_EDIT) ? '' : 'DISABLED';

    /*****************
     *
     * Submitted form?
     *
     *****************/
     
    if (isset($_POST['button']) && $ALLOW_EDIT) {
    
        if (get_magic_quotes_gpc())
            $_POST['summary'] =  stripslashes($_POST['summary']);
        
        // Update general match data
        status($m->update(array(
            'submitter_id'  => $_SESSION['coach_id'],
            'stadium'       => $_POST['stadium'],
            'gate'          => (int) ($_POST['gate'] * 1000),
            'fans'          => (int) $_POST['fans'],
            'ffactor1'      => $_POST['ff_1'],
            'ffactor2'      => $_POST['ff_2'],
            'income1'       => $_POST['inc_1'] ? $_POST['inc_1'] * 1000 : 0,
            'income2'       => $_POST['inc_2'] ? $_POST['inc_2'] * 1000 : 0,
            'team1_score'   => $_POST['result1'] ? $_POST['result1'] : 0,
            'team2_score'   => $_POST['result2'] ? $_POST['result2'] : 0,
            'smp1'          => (int) $_POST['smp1'],
            'smp2'          => (int) $_POST['smp2'],
            'tcas1'         => (int) $_POST['tcas1'],
            'tcas2'         => (int) $_POST['tcas2'],
            'fame1'         => (int) $_POST['fame1'],
            'fame2'         => (int) $_POST['fame2'],
            'tv1'           => (int) $_POST['tv1']*1000,
            'tv2'           => (int) $_POST['tv2']*1000,
            'comment'       => $_POST['summary'] ? $_POST['summary'] : '',
        )));

        // Pictures.
        $m->savePics();

        // Update match's player data
        foreach (array(1 => $team1, 2 => $team2) as $id => $t) {
        
            /* Save ordinary players */
        
            foreach ($t->getPlayers() as $p) {
            
                if (!player_validation($p, $m)){
                	continue;
                }
                
                // Set zero entry for MNG player(s).
                if ($p->getStatus($m->match_id) == MNG) {
                    $_POST['mvp_' . $p->player_id]      = 0;
                    $_POST['cp_' . $p->player_id]       = 0;
                    $_POST['td_' . $p->player_id]       = 0;
                    $_POST['intcpt_' . $p->player_id]   = 0;
                    $_POST['bh_' . $p->player_id]       = 0;
                    $_POST['si_' . $p->player_id]       = 0;
                    $_POST['ki_' . $p->player_id]       = 0;
                    $_POST['inj_' . $p->player_id]      = NONE;
                    $_POST['agn1_' . $p->player_id]     = NONE;
                    $_POST['agn2_' . $p->player_id]     = NONE;
                }
                
                $m->entry(array(
                    'player_id' => $p->player_id,
                    'team_id'   => $t->team_id,
                    /* 
                        Regarding MVP: We must check for isset() since checkboxes are not sent at all when not checked! 
                        We must also test for truth since the MNG-status exception above defines the MNG status, and thereby passing isset() here!
                    */
                    'mvp'     => (isset($_POST['mvp_' . $p->player_id]) && $_POST['mvp_' . $p->player_id]) ? 1 : 0,
                    'cp'      => $_POST['cp_' . $p->player_id],
                    'td'      => $_POST['td_' . $p->player_id],
                    'intcpt'  => $_POST['intcpt_' . $p->player_id],
                    'bh'      => $_POST['bh_' . $p->player_id],
                    'si'      => $_POST['si_' . $p->player_id],
                    'ki'      => $_POST['ki_' . $p->player_id],
                    'inj'     => $_POST['inj_' . $p->player_id],
                    'agn1'    => $_POST['agn1_' . $p->player_id],
                    'agn2'    => $_POST['agn2_' . $p->player_id],
                ));
            }
            
            /* 
                Save stars entries. 
            */

            foreach ($stars as $star) {
                $s = new Star($star['id']);
                if (isset($_POST['team_'.$star['id']]) && $_POST['team_'.$star['id']] == $id) {
                    $sid = $s->star_id;

                    $m->entry(array(
                        'player_id' => $sid,
                        'team_id'   => $t->team_id,
                        
                        'mvp'     => (isset($_POST["mvp_$sid"]) && $_POST["mvp_$sid"]) ? 1 : 0,
                        'cp'      => $_POST["cp_$sid"],
                        'td'      => $_POST["td_$sid"],
                        'intcpt'  => $_POST["intcpt_$sid"],
                        'bh'      => $_POST["bh_$sid"],
                        'si'      => $_POST["si_$sid"],
                        'ki'      => $_POST["ki_$sid"],
                    ));
                }
                else {
                    $s->rmMatchEntry($m->match_id, $t->team_id);
                }
            }
            
            /* 
                Save mercenary entries. 
            */
            
            Mercenary::rmMatchEntries($m->match_id, $t->team_id); // Remove all previously saved mercs in this match.
            for ($i = 0; $i <= 50; $i++)  { # We don't expect over 50 mercs. This is just some large random number.
                $idm = '_'.ID_MERCS.'_'.$i;
                if (isset($_POST["team$idm"]) && $_POST["team$idm"] == $id) {
                    $m->entry(array(
                        'player_id' => ID_MERCS,
                        'team_id'   => $t->team_id,
                        'nr'        => $i,
                        'skills'    => $_POST["skills$idm"],                    
                        
                        'mvp'     => (isset($_POST["mvp$idm"]) && $_POST["mvp$idm"]) ? 1 : 0,
                        'cp'      => $_POST["cp$idm"],
                        'td'      => $_POST["td$idm"],
                        'intcpt'  => $_POST["intcpt$idm"],
                        'bh'      => $_POST["bh$idm"],
                        'si'      => $_POST["si$idm"],
                        'ki'      => $_POST["ki$idm"],
                    ));
                }
            }
        }

        // Refresh objects used to display form.
        $m = new Match($match_id);
        $team1 = new Team($m->team1_id);
        $team2 = new Team($m->team2_id);
    }
    
    // Match comment made?
    if (isset($_POST['msmrc']) && is_object($coach)) {
        status($m->newComment($coach->coach_id, $_POST['msmrc']));
    }
    
    // Match comment delete?
    if (isset($_POST['type']) && $_POST['type'] == 'cmtdel' && is_object($coach)) {
        status($m->deleteComment($_POST['cid']));
    }

    /****************
     *
     * Generate form 
     *
     ****************/

    title((($m->team1_id) ? $m->team1_name : '<i>'.$lng->getTrn('secs/fixtures/undecided').'</i>') . " - " . (($m->team2_id) ? $m->team2_name : '<i>'.$lng->getTrn('secs/fixtures/undecided').'</i>'));
    $CP = 8; // Colspan.

    $did = get_alt_col('tours', 'tour_id', $m->f_tour_id, 'f_did'); // For below match relations (league, division etc.) table.
    ?>
    <table>
    <tr><td><b>League</b>:</td><td><?php echo get_alt_col('leagues', 'lid', get_alt_col('divisions', 'did', $did, 'f_lid'), 'name');?></td></tr>
    <tr><td><b>Division</b>:</td><td><?php echo get_alt_col('divisions', 'did', $did, 'name');?></td></tr>
    <tr><td><b>Tournament</b>:</td><td><?php echo get_alt_col('tours', 'tour_id', $m->f_tour_id, 'name');?></td></tr>
    <tr><td><b>Date played</b>:</td><td><?php echo ($m->is_played) ? textdate($m->date_played) : '<i>Not yet played</i>';?></td></tr>
    </table>

    <?php
    
    //configuration for the template
    $data = array(
    	//Text strings from the language system
    	"lang_click"	=> $lng->getTrn('secs/fixtures/report/click'),
    	"lang_help"		=> $lng->getTrn('secs/fixtures/report/help'),
    	"lang_forhelp"	=> $lng->getTrn('secs/fixtures/report/forhelp'),
    	"lang_info" 	=> $lng->getTrn('secs/fixtures/report/info'),
    	"lang_stad" 	=> $lng->getTrn('secs/fixtures/report/stad'),
    	"lang_gate" 	=> $lng->getTrn('secs/fixtures/report/gate'),
    	"lang_fans" 	=> $lng->getTrn('secs/fixtures/report/fans'),
    	"lang_teams" 	=> $lng->getTrn('secs/fixtures/report/teams'),
    	"lang_score" 	=> $lng->getTrn('secs/fixtures/report/score'),
    	"lang_treas" 	=> $lng->getTrn('secs/fixtures/report/treas'),
    	"lang_ff" 		=> $lng->getTrn('secs/fixtures/report/ff'),
    	"lang_smp"	 	=> $lng->getTrn('secs/fixtures/report/smp'),
    	"lang_tcas" 	=> $lng->getTrn('secs/fixtures/report/tcas'),
    	"lang_pts"		=> $lng->getTrn('secs/fixtures/report/pts'),
    	"lang_fame"	 	=> $lng->getTrn('secs/fixtures/report/fame'),
    	"lang_tv" 		=> $lng->getTrn('secs/fixtures/report/tv'),
    	"CP" 			=> $CP,	//colspan
    	"DIS" 			=> $DIS,	//fields disabled?
    	"fans"			=> $m->fans,
    	"gate" 			=> ($m->gate ? $m->gate/1000 : 0),
   	);
   	
   	$participatingteam = array();	//array to hold info about the teams in the match

   	$tmp = array(
   		"teamnumber"	=> 1,
   		"name" 			=> $m->team1_name,
    	"score" 		=> $m->team1_score,
    	"income" 		=> ((int) $m->income1)/1000,
    	"ff_up" 		=> ($m->ffactor1 == 1) ? "checked='checked'" : '',	//ff up
    	"ff_nochange" 	=> ($m->ffactor1 == 0) ? "checked='checked'" : '',	//ff no change
    	"ff_down" 		=> ($m->ffactor1 == -1)	 ? "checked='checked'" : '',	//ff down
    	"smp"			=> $m->smp1,			//Sportsmanship points
    	"tcas"			=> $m->tcas1,
    	"fame"			=> $m->fame1,
    	"value"			=> ($m->is_played) ? $m->tv1/1000 : $team1->value/1000
   	);
   	array_push($participatingteam,$tmp);	//add team1 to the array;
    
    $tmp = array(
    	"teamnumber" 	=> 2,
   		"name" 			=> $m->team2_name,
    	"score" 		=> $m->team2_score,
    	"income" 		=> ((int) $m->income2)/1000,
    	"ff_up" 		=> ($m->ffactor2 == 1) ? "checked='checked'" : '',	//ff up
    	"ff_nochange" 	=> ($m->ffactor2 == 0) ? "checked='checked'" : '',	//ff no change
    	"ff_down" 		=> ($m->ffactor2 == -1)	 ? "checked='checked'" : '',	//ff down
    	"smp"			=> $m->smp2,			//Sportsmanship points
    	"tcas"			=> $m->tcas2,
    	"fame"			=> $m->fame2,
    	"value"			=> ($m->is_played) ? $m->tv2/1000 : $team2->value/1000
   	);
   	array_push($participatingteam,$tmp);	//add team2 to the array
    
    $data["participatingteams"] = $participatingteam;	//add the participating teams array to the template data array
    
    
    $teams = Team::getTeams();
    objsort($teams, array('+name'));
    $stad = ($m->stadium) ? $m->stadium : $m->team1_id;
    $tmp = array();
    foreach ($teams as $_t) {
    	$thisTeam = array();
    	$thisTeam["SELECTED"] = ($stad == $_t->team_id ? "selected" : '');
    	$thisTeam["team_id"] = $_t->team_id;
    	$thisTeam["team_name"] = $_t->name;
    	if ($_t->team_id == $m->team1_id || $_t->team_id == $m->team2_id){
    		$thisTeam["color"] = COLOR_HTML_READY;	
    	}
    	$thisTeam["selected_name"] = ($_t->team_id == $m->team1_id || $_t->team_id == $m->team2_id);
    	
    	array_push($tmp, $thisTeam);
    }
    
    $data["team"] = $tmp;
    
   	
  	//ready the template system 
    include_once("lib/Mustache.php");
    $mus = new Mustache;
    $template = file_get_contents("templates/matchreport_team.ms");
    
    //render the template
    echo $mus->render($template, $data);
    
    /////////
    
    $data = array(
    	"lang_report" 		=> $lng->getTrn('secs/fixtures/report/report'),
    	"lang_summary"		=> $lng->getTrn('secs/fixtures/report/summary'),
    	"lang_photos"		=> $lng->getTrn('secs/fixtures/report/photos'),
    	"lang_pnote"		=> $lng->getTrn('secs/fixtures/report/pnote'),
    	"lang_photo"		=> $lng->getTrn('secs/fixtures/report/photo'),
    	"lang_occ"			=> $lng->getTrn('secs/fixtures/report/occ'),
    	"lang_add"			=> $lng->getTrn('secs/fixtures/report/add'),
    	"lang_save"			=> $lng->getTrn('secs/fixtures/report/save'),
    	"comment"			=> $m->comment,
    	"match_id"			=> $m->match_id,
    	"ID_MERCS"			=> ID_MERCS
    	
    );
    $teamCollection = array();	//used to store each team, meant to be added to the $data array later

    foreach (array(1 => $team1, 2 => $team2) as $id => $t) {
    	$playerCollection = array();	//this teams players
    	$tmpTeam = array(
   	 		"team_id"		=> $t->team_id,
   	 		"name"			=> $t->name,
   	 		"teamnumber"	=> $id
    	);
		foreach ($t->getPlayers() as $p) {
			
			// Fetch player data from match
		    $status = $p->getStatus($m->match_id);
		    $mdat   = $p->getMatchData($m->match_id);
		    
		    //Determine of the player is eligble to participate in the match (not dead and not jorneyman)
   			if (!player_validation($p, $m)){
   				continue;
   			}
			
			//Set correct background color, if needed
			//TODO: Redo as a class
			$color = "";
			if ($p->is_journeyman){
				$color = COLOR_HTML_JOURNEY;
			} elseif ($status == MNG) {
				$color = COLOR_HTML_MNG;
			}
		
			$tmpPlayer = array(
				"backgroundColor" 	=> $color,
				"nr"				=> $p->nr,
				"name"				=> $p->name,
				"position"			=> $p->position,
				"status"			=> ($status == MNG ? '&nbsp;[MNG]' : ''),
				"mvp_checked"		=> ($mdat['mvp'] ? 'checked="checked ' : ''),
				"DIS"				=> (($DIS || ($status == MNG)) ? 'disabled="disabled"' : ''),
				"player_id"			=> $p->player_id,
				"cp_value"			=> $mdat["cp"],
				"td_value"			=> $mdat["td"],
				"intcpt_value"		=> $mdat["intcpt"],
				"bh_value"			=> $mdat["bh"],
				"si_value"			=> $mdat["si"],
				"ki_value"			=> $mdat["ki"],
				"NONE"				=> NONE,
				"MNG"				=> MNG,
				"NI"				=> NI,
				"MA"				=> MA,
				"ST"				=> ST,
				"AG"				=> AG,
				"AV"				=> AV,
				"DEAD"				=> DEAD
			);
			
			switch($mdat['inj']){
				case NONE:
					$tmpPlayer['inj_none_selected'] = true;
					break;
				case MNG:
					$tmpPlayer['inj_mng_selected'] = true;
					break;
				case NI:
					$tmpPlayer['inj_ni_selected'] = true;
					break;
				case MA:
					$tmpPlayer['inj_ma_selected'] = true;
					break;
				case AV:
					$tmpPlayer['inj_av_selected'] = true;
					break;
				case AG:
					$tmpPlayer['inj_ag_selected'] = true;
					break;
				case ST:
					$tmpPlayer['inj_st_selected'] = true;
					break;
				case DEAD:
					$tmpPlayer['inj_dead_selected'] = true;
					break;
			}
			
			$agingArray = array();
			
			//build data for each of the two aging fields
			foreach(array(1 => "agn1", 2 => "agn2") as $id => $aging){
				
				$tmp = array();
				$tmp['id'] = $aging;
				
				switch($mdat[$aging]){
					case NONE:
						$tmp['none_selected'] = true;
   						break;
   					case NI:
   						$tmp['ni_selected'] = true;
   						break;
   					case MA:
   						$tmp['ma_selected'] = true;
   						break;
   					case AV:
   						$tmp['av_selected'] = true;
   						break;
   					case AG:
   						$tmp['ag_selected'] = true;
   						break;
   					case AV:
   						$tmp['av_selected'] = true;
   						break;
   					case ST:
   						$tmp['st_selected'] = true;
   						break;
				}
				array_push($agingArray, $tmp);
			}
			$tmpPlayer["aging"] = $agingArray;
   				
   			//Add the player to the playerCollection for this team
   			array_push($playerCollection,$tmpPlayer);
   			
   		}
   		if ($rules['enable_stars_mercs']) {
   			
   			$data['mercsEnabled'] = true;
   			$mercCollection = array();
   			
   			foreach ($stars as $name => $d) {
   				$d['name'] = $name;
   				if (in_array($t->race, $d['teams'])){
   					$d['color'] = COLOR_HTML_READY;
   				}
   				array_push($mercCollection, $d);
   			}
       }    
       
       $tmpTeam['mercs'] = $mercCollection;

       $tmpTeam["players"] = $playerCollection;
       array_push($teamCollection, $tmpTeam);		//add teamonly info the the temp team collection array
	}
	
	$data["teams"] = $teamCollection;

	$rows = 3; // Number of rows of pics.
	$ppr = 4; // Pics per row.
	
	$picArray = array();
	for ($pics = $m->getPics(), $i = 1; $i <= $rows; $i++) { // Limit to three rows of pics.
		for ($j = 1; $j <= $ppr && ($pic = array_shift($pics)); $j++) {
			$tmp = array();
			$tmp['id'] = (($i-1)*$ppr+$j);
			$tmp['src'] = $pic;
			array_push($picArray, $tmp);
		}
	}
	//add the image array to the data object
	$data['pics'] = $picArray;
	
	//upload fields
	$uploadArray = array();
	for ($i = 1; $i <= 10; $i++) {
		$tmp = array();
		$tmp['id'] = $i;
		if ($m->picExists($i)){
			$tmp['image'] = true;
		}
		array_push($uploadArray, $tmp);
	}
	$data['uploadphotos'] = $uploadArray;
	
	//load template file	
	$template = file_get_contents("templates/matchreport_teaminfo.ms");
	
	//render the template
	echo $mus->render($template, $data);

    $CDIS = (!is_object($coach)) ? 'DISABLED' : '';
    ?>
    <table class="match_form">
        <tr>
            <td colspan='13' class='dark'><b><a href="javascript:void(0)" onclick="obj=document.getElementById('msmrc'); if (obj.style.display != 'none'){obj.style.display='none'}else{obj.style.display='block'};">[+/-]</a> <?php echo $lng->getTrn('secs/fixtures/report/msmrc');?></b></td>
        </tr>
        <tr>
            <td class='seperator'></td>
        </tr>
        <tr>
            <td>
                <div id="msmrc">
                    <?php echo $lng->getTrn('secs/fixtures/report/existCmt');?>: <?php if (!$m->hasComments()) echo '<i>'.$lng->getTrn('secs/fixtures/report/none').'</i>';?><br><br>
                    <?php
                    foreach ($m->getComments() as $c) {
                        echo "Posted $c->date by <b>$c->sname</b> 
                            <form method='POST' name='cmt$c->cid' style='display:inline; margin:0px;'>
                            <input type='hidden' name='type' value='cmtdel'>
                            <input type='hidden' name='cid' value='$c->cid'>
                            <a href='javascript:void(0);' onClick='document.cmt$c->cid.submit();'>[".$lng->getTrn('secs/fixtures/report/delete')."]</a>
                            </form>
                            :<br>".$c->txt."<br><br>\n";
                    }
                    
                    ?>
                </div>
            </td>
        </tr>
        <tr>
            <td>
                <form method="POST">
                <?php echo $lng->getTrn('secs/fixtures/report/newCmt');?>:<br>
                <textarea name="msmrc" rows='5' cols='100' <?php echo $CDIS;?>><?php echo $lng->getTrn('secs/fixtures/report/writeNewCmt');?></textarea>
                <br>
                <input type="submit" value="<?php echo $lng->getTrn('secs/fixtures/report/postCmt');?>" name="new_msmrc" <?php echo $CDIS;?>>
                </form>
            </td>
        </tr>
    </table>
    <script language='JavaScript' type='text/javascript'>
        document.getElementById('msmrc').style.display = 'none';
    </script>
    <?php
    
    /* 
        Now, we call javascript routine(s) to fill out stars and mercs rows, if such entries exist in database. 
    */
    
    $i = 0; // Counter. Used to pass PHP-data to Javascript.
    foreach (array(1 => $team1->team_id, 2 => $team2->team_id) as $id => $t) {
        foreach (Star::getStars(STATS_TEAM, $t, STATS_MATCH, $m->match_id) as $s) {
            $s->setStats(false,false, STATS_MATCH, $m->match_id); // Set the star's stats fields to the saved values in the database for this match.
            echo "<script language='JavaScript' type='text/javascript'>\n";
            echo "var mdat$i = [];\n";
            foreach (array('mvp', 'cp', 'td', 'intcpt', 'bh', 'ki', 'si') as $f) {
                echo "mdat${i}['$f'] = ".$s->$f.";\n";
            }
            echo "existingStarMerc($id, $s->star_id, mdat$i);\n";
            echo "</script>\n";
            $i++;
        }
        
        foreach (Mercenary::getMercsHiredByTeam($t, $m->match_id) as $merc) {
            echo "<script language='JavaScript' type='text/javascript'>\n";
            echo "var mdat$i = [];\n";
            foreach (array('mvp', 'cp', 'td', 'intcpt', 'bh', 'ki', 'si', 'skills') as $f) {
                echo "mdat${i}['$f'] = ".$merc->$f.";\n";
            }
            echo "existingStarMerc($id, ".ID_MERCS.", mdat$i);\n";
            echo "</script>\n";
            $i++;
        }
    }
}

function player_validation($p, $m) {

    if (!is_object($p) || !is_object($m))
        return false;
        
    // Existing match?                    
    if ($m->is_played) {

        // Skip if player is bought after match was played.
        if ($p->date_bought > $m->date_played)
            return false;
    
        // If sold before this match was played.
        if ($p->is_sold && $p->date_sold < $m->date_played)
            return false;
        
        // Player died in a earlier match.
        if ($p->getStatus($m->match_id) == DEAD)
            return false;
    }
    // New match?
    else {
    
        if ($p->is_dead || $p->is_sold)
            return false;
    }
    
    return true;
}

